﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.Mvc;
using Complaint.Common;

namespace Complaint.ActionResults
{
    public class CaptchaActionResult : ActionResult
    {
        public string RandomWord { get; set; }

        #region Overrides of ActionResult

        /// <summary>
        /// Enables processing of the result of an action method by a custom type that inherits from <see cref="T:System.Web.Mvc.ActionResult"/>.
        /// </summary>
        /// <param name="context">The context within which the result is executed.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            RenderCaptchaImage(context);
        }

        private void RenderCaptchaImage(ControllerContext context)
        {
            var image = new Bitmap(context.HttpContext.Server.MapPath("~/Images/image.png"));
            var g = Graphics.FromImage(image);
            var area = new Rectangle(0, 0, image.Width - 1, image.Height - 1);
            var pen = new Pen(Color.SkyBlue);

            var lgBrush =
                new LinearGradientBrush(
                    area,
                    GetColorFromRGB(ConfigHelper.GetConfigValue("CaptchaBGGradientStartRGB")),
                    GetColorFromRGB(ConfigHelper.GetConfigValue("CaptchaBGGradientFinishRGB")),
                    LinearGradientMode.Vertical);

            g.FillRectangle(lgBrush, area);
            g.DrawRectangle(pen, area);

            var brush = new SolidBrush(Color.Black);
            var random = new Random();
            var charPosition = 10;

            var charCount = RandomWord.Length;
            for (var i = 0; i < charCount; i++)
            {
                var c = RandomWord.Substring(i, 1);
                g.DrawString(c, new Font("arial", random.Next(16, 25)), brush, charPosition, 10);
                charPosition += 17;
            }
            context.HttpContext.Response.ContentType = "image/jpeg";
            image.Save(context.HttpContext.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        #endregion

        private static Color GetColorFromRGB(string strRGB)
        {
            var rgb = strRGB.Split(new[] { ',' });
            Color color;
            try
            {
                var r = int.Parse(rgb[0]);
                var g = int.Parse(rgb[1]);
                var b = int.Parse(rgb[2]);
                color = Color.FromArgb(r, g, b);
            }
            catch (IndexOutOfRangeException ixe)
            {
                throw new ArgumentException("Invalid background gradient color RGB setting.", ixe);
            }

            return color;
        }
    }
}